package com.frame.hander;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

/**
 * @author LRC
 * @createDate 2015年5月19日
 * @description 百度地图API
 */
public class MapHander {

	private static String readAll(Reader rd) throws IOException {
		StringBuilder sb = new StringBuilder();
		int cp;
		while ((cp = rd.read()) != -1) {
			sb.append((char) cp);
		}
		return sb.toString();
	}

	public static JSONObject readJsonFromUrl(String url) throws IOException,
			JSONException {
		InputStream is = new URL(url).openStream();
		try {
			BufferedReader rd = new BufferedReader(new InputStreamReader(is,
					Charset.forName("UTF-8")));
			String jsonText = readAll(rd);
			JSONObject json = JSONObject.fromObject(jsonText);
			return json;
		} finally {
			is.close();
		}
	}

	public static String readTextFromUrl(String url) throws IOException,
			JSONException {
		InputStream is = new URL(url).openStream();
		try {
			BufferedReader rd = new BufferedReader(new InputStreamReader(is,
					Charset.forName("UTF-8")));
			String text = readAll(rd);
			return text;
		} finally {
			is.close();
		}
	}

	private static String locationUrl = "http://api.map.baidu.com/location/ip?ak=lhNIbpanQnUEVfBYEKGOqxio&ip=";
	private static String reLocationUrl = "http://api.map.baidu.com/geocoder/v2/?ak=lhNIbpanQnUEVfBYEKGOqxio&callback=renderReverse&output=json&pois=0&location=";

	public static JSONObject getLocation(String ip) {
		try {
			JSONObject json = readJsonFromUrl(locationUrl + ip);
			String location = null;
			if (json != null) {
				System.out.println(json);
				JSONObject point = json.getJSONObject("content").getJSONObject(
						"point");
				System.out.println(point);
				location = point.getString("y")+","+point.getString("x");
				String textLocation = readTextFromUrl(reLocationUrl
						+ location);
				String jsonText = textLocation.substring("renderReverse&&renderReverse(".length(),textLocation.lastIndexOf(")"));
				return JSONObject.fromObject(jsonText);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		JSONObject location = getLocation("117.140.9.247");
		System.out.println(location);
	}
}
